package cn.dubito.springboot.learning.converter;

import cn.dubito.springboot.learning.dataobject.OrderDetail;
import cn.dubito.springboot.learning.dto.OrderDTO;
import cn.dubito.springboot.learning.enums.ResultEnum;
import cn.dubito.springboot.learning.exception.SellException;
import cn.dubito.springboot.learning.param.OrderParam;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author liliang
 * @description:
 * @date 2018/1/15.
 */
@Slf4j
public class OrderParamToOrderDto {

    public static OrderDTO convert(OrderParam orderParam) {
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setBuyerName(orderParam.getName());
        orderDTO.setBuyerPhone(orderParam.getPhone());
        orderDTO.setBuyerAddress(orderParam.getAddress());
        orderDTO.setBuyerOpenid(orderParam.getOpenid());
        Gson gson = new Gson();
        List<OrderDetail> orderDetailList;
        try {
            orderDetailList = gson.fromJson(orderParam.getItems(), new TypeToken<List<OrderDetail>>() {
            }.getType());
        } catch (Exception e) {
            log.error("[创建订单] 对象转换异常,参数格式不正确,items={}", orderParam.getItems());
            throw new SellException(ResultEnum.PARAM_ERROR);
        }
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }
}
